from git import Repo
from pathlib import Path
from datetime import datetime
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# 仓库信息
repos_info = [
    {
        "name": "SteamTools",
        "link": "https://gitee.com/rmbgame/SteamTools",
        "script_path": "report-SteamTools.py"
    },
    {
        "name": "openeuler-jenkins",
        "link": "https://gitee.com/openeuler/openeuler-jenkins",
        "script_path": "report-openeuler-jenkins.py"
    }
]

# 初始化Markdown报告
md = "# Cross-Repository Comparison Report\n\n"
md += "---\n\n"

# 准备数据
all_commit_dates = []
all_cumulative_commits = []
total_commits = {}

for repo_info in repos_info:
    repo_name = repo_info["name"]
    repo_link = repo_info["link"]

    # 克隆或加载本地仓库
    if Path(repo_name).exists():
        repo = Repo(repo_name)
    else:
        print(f"Cloning Repo {repo_name}...")
        repo = Repo.clone_from(repo_link, repo_name)
        print(f"Finished Cloning {repo_name}!")

    # 获取所有提交
    repo_commits = list(repo.iter_commits())
    total_commits[repo_name] = len(repo_commits)

    # 累计提交增长数据
    commit_dates = [datetime.fromtimestamp(commit.authored_date) for commit in repo_commits]
    sorted_indices = np.argsort(commit_dates)
    commit_dates = [commit_dates[i] for i in sorted_indices]
    cumulative_commits = np.arange(1, len(repo_commits) + 1)

    all_commit_dates.append(commit_dates)
    all_cumulative_commits.append(cumulative_commits)

# 可视化：累计提交增长对比
plt.figure(figsize=(12, 6))
for i, repo_info in enumerate(repos_info):
    repo_name = repo_info["name"]
    plt.plot(all_commit_dates[i], all_cumulative_commits[i], label=repo_name)

plt.title("Cumulative Commit Growth Comparison")
plt.xlabel("Time")
plt.ylabel("Cumulative Number of Commits")
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
Path("visuals").mkdir(parents=True, exist_ok=True)
cumulative_growth_path = f'visuals/cumulative_commit_growth_comparison.png'
plt.savefig(cumulative_growth_path)
plt.close()

md += "## Cumulative Commit Growth Comparison\n\n"
md += f"![Cumulative Commit Growth Comparison]({cumulative_growth_path})\n\n"

# 可视化：提交总数对比
repo_names = list(total_commits.keys())
commit_counts = list(total_commits.values())

plt.figure(figsize=(10, 6))
sns.barplot(x=repo_names, y=commit_counts)
plt.title("Total Commits Comparison")
plt.xlabel("Repository names")
plt.ylabel("Total number of commits")
plt.tight_layout()
total_commits_path = f'visuals/total_commits_comparison.png'
plt.savefig(total_commits_path)
plt.close()

md += "## Total Commits Comparison\n\n"
md += f"![Total Commits Comparison]({total_commits_path})\n\n"

# 写入Markdown文件
Path("comparison_report.md").write_text(md, "UTF-8")